package ocs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class AccountHelper {

    Properties settings;

    Account ovsAccount;

    Account googleAccount;

    private String accountFilePath;

    AccountHelper(String accountFilePath) throws FileNotFoundException, IOException {
        this.accountFilePath = accountFilePath;

        loadAccountFile();
        loadAccounts();
    }

    private void loadAccounts() {
        String authToken = settings.getProperty("ovs.authtoken");
        String login = settings.getProperty("ovs.login");
        String password = settings.getProperty("ovs.password");
        ovsAccount = new Account(login, password, authToken);

        authToken = settings.getProperty("google.authtoken");
        login = settings.getProperty("google.login");
        password = settings.getProperty("google.password");
        googleAccount = new Account(login, password, authToken);
    }

    private void loadAccountFile() throws IOException, FileNotFoundException {
        settings = new Properties();
        File cookiesFile = new File(accountFilePath);
        if (!cookiesFile.exists()) {
            cookiesFile.createNewFile();
        }
        settings.load(new FileReader(cookiesFile));
    }

    public void saveAccounts(Account gooAccount, Account ovsAccount) throws IOException {
        if (gooAccount.getAuthToken() != null) {
            settings.setProperty("google.authtoken", gooAccount.getAuthToken());
        }
        if (gooAccount.getLogin() != null) {
            settings.setProperty("google.login", gooAccount.getLogin());
        }
        if (gooAccount.getPassword() != null) {
            settings.setProperty("google.password", gooAccount.getPassword());
        }
        if (ovsAccount.getAuthToken() != null) {
            settings.setProperty("ovs.authtoken", ovsAccount.getAuthToken());
        }
        if (ovsAccount.getLogin() != null) {
            settings.setProperty("ovs.login", ovsAccount.getLogin());
        }
        if (ovsAccount.getPassword() != null) {
            settings.setProperty("ovs.password", ovsAccount.getPassword());
        }

        save();
    }

    private void save() throws IOException {
        settings.store(new FileWriter(accountFilePath), "OCS user settings");
    }

    public String getGoogleAuthToken() {
        return googleAccount.getAuthToken();
    }

    public String getOvsAuthToken() {
        return ovsAccount.getAuthToken();
    }

    public Account getOvsAccount() {
        return ovsAccount;
    }

    public Account getGoogleAccount() {
        return googleAccount;
    }
}
